﻿<?php
/**
 * 运单费用
 */
class Application_Model_VisitingServer extends Application_Model_DomainObject implements Application_Model_PayInterface{
    
    protected $_id;
    protected $_dateCreated;//创建时间
    protected $_userId;//用户id
    protected $_waresName;//商品名称
    protected $_waresDescribe;//商品描述 
    protected $_estimateWeight;//预付重量
    protected $_estimateVolume;//预估体积
    protected $_inlandCityId;//国内城市id
    protected $_inlandTownId;//市级id
    protected $_inlandAddress;//国内取件地址
    protected $_inlandUser;//国内取件联系人 
    protected $_inlandPhone;//联系人电话
    protected $_inlandMoney;//国内运费
    protected $_actualCnShipFee;//实际国内运费
    protected $_guaranteeFee;//保证金
    protected $_status;//前台状态
    protected $_interior;//内部状态
    protected $_inlandLogistics;//国内运单物流号
    protected $_isWay; //是否发起国际运单 0不发起 1发起
    protected $_wayId;//国际运单id
    protected $_isWayMoney;//是否支付国际运费 
    protected $_advanceMoney;//国际运单运费(预交)
    protected $_isArrears;//是否补交运费 0 不需要补交 1 要补交
    protected $_arrearsMoney;//补交金额
    protected $_isPay;//是否已经补交
    protected $_remark;//备注
    protected $_interiorRemark;//内部状态
    protected $_visitingNo;//编号
    protected $_datePaid;//付款时间
    protected $_sfNo;//顺丰单号
    protected $_problem;//异常状态
    protected $_packageSize; //包裹尺寸
    protected $_inlandShipType;//国内发货渠道
    protected $_isDel; //是否已经删除 0正常 1 已删除
    protected $_itemType;//商品类型 
    protected $_problemNote;//问题描述
    protected $_ckPass;//判断是否通过

    /**
     *  等待付款
     */
    const STATUS_WaitPay = 0;
    /**
     * 等待受理
     */
    const STATUS_Processing = 1;
    /**
     * 已受理待取件
     */
    const STATUS_Confrimed = 2;
    /**
     * 已取件待入库
     */
    const STATUS_Delivery = 3;
    /**
     * 已入库
     */
    const STATUS_InStore = 4;
    /**
     * 已发国际
     */
    const STATUS_Launch = 5;
    /**
     * 存入云仓库完成
     */
    const STATUS_Complete = 6;
    /**
     * 结算补交国内运费
     */
    const STATUS_Payfreight = 7;
    /**
     * 补交款
     */
    const STATUS_Payingmoney = 8;
    /**
     * 取消退件
     */
    const STATUS_Cancel = -1;
    /**
     * 快递遗失
     */
    const STATUS_Lose = -2;
    /**
     * 渠道冲突
     */
    const STATUS_ChannelConflict = -3;
    /**
     * 取件异常
     */
    const STATUS_DeliveryProblem = -4;
    /**
     * 未付款
     */
    const Interior_WaitPay = 0;
    /**
     * 未受理
     */
    const Interior_Processing = 1;
    /**
     * 已受理待通知
     */
    const Interior_Confrimed = 2;
    /**
     * 通知顺丰取件
     */
    const Interior_InformDelivery = 3;
    /**
     * 已取件，在途中
     */
    const Interior_Delivery = 10;
    /**
     * 已入库
     */
    const Interior_InStore = 11;
    /**
     * 运送超期
     */
    const Interior_ShipOutTime = 12;
    /**
     * 已打包待审单
     */
    const Interior_Pack = 13;
    /**
     * 已审单待补交款
     */
    const Interior_Inspections = 14;
    /**
     * 补交款
     */
    const Interior_Payingmoney = 18;
    /**
     * 已补交待发出
     */
    const Interior_ArrearsFee = 15;
    /**
     * 存入云仓库完成
     */
    const Interior_Complete = 16;
    /**
     * 结算补交国内运费
     */
    const Interior_Payfreight = 17;
    /**
     * 已发国际
     */
    const Interior_Launch = 30;
    /**
     * 快递丢包
     */
    const Interior_Lose = 22;
    /**
     * 渠道冲突
     */
//    const Interior_ChannelConflict = 23;
    /**
     * 取件异常
     */
    const Interior_DeliveryProblem = 24;
    /**
     * 取消退件
     */
    const Interior_Cancel = -1;
    /**
     * 初始化
     */
    const Problem_Default = 0;
    /**
     * 出现问题
     */
    const Problem_AppearProblem = 1;
    /**
     * 解决问题
     */
    const Problem_SolveProblem = 2;
    /**
     * 取消
     */
    const Problem_Cancel = 3;


    public function getPayName() {
        if($this->_isWay == 0){
            return "悠奇-国内上门取件押金";
        } else {
            return "悠奇-国内上门取件发往海外";
        }
    }
    
    public function getPayCommen() {
        return "国内上门取流水号：".$this->_visitingNo;
    }
    
     public function isRepeatPay() {
        if($this->_interior == self::Interior_WaitPay || $this->_interior == self::Interior_Payingmoney || $this->_interior == self::Interior_Payfreight){
            return true;
        } 
        return false;
    }
    
    public function getMoney(){
        if($this->_isWay == 0){
            return $this->_guaranteeFee;
        } else {
            return $this->_advanceMoney;
        }
    }
    
    public function getBillNo(){
        return $this->_visitingNo;
    }
    
    public function getPayDescription() {
        if($this->_isWay == 0){
            return "支付上门取件押金";
        } else {
            return "支付上门取件国内运费及国际运费";
        }
    }
   
   public static function getInteriorCorrect() {
        return array(
            self::Interior_Confrimed => array("待受理", "已受理")
            , self::Interior_InformDelivery => array("通知顺丰取件", "通知顺丰取件")
            , self::Interior_Delivery => array("待取件", "已取件")
            , self::Interior_InStore => array("待入库", "已入库")
            , self::Interior_Complete => array("待结算","结算")
        );
   }
   
   public static function getInteriorCorrect2() {
        return array(
            self::Interior_Confrimed => array("待受理", "已受理")
            , self::Interior_InformDelivery => array("通知顺丰取件", "通知顺丰取件")
            , self::Interior_Delivery => array("待取件", "已取件")
            , self::Interior_InStore => array("待入库", "已入库")
            , self::Interior_Pack => array("待打包", "已打包")
            , self::Interior_Inspections => array("待审单", "已审单")
            , self::Interior_ArrearsFee => array("等待补交款", "已交款")
            , self::Interior_Launch => array("未启用", "启用")
        );
   }
    
   
   public function setPaid() {
        if($this->_interior == self::Interior_WaitPay){
            $this->_status = self::STATUS_Processing;
            $this->_interior = self::Interior_Processing;
            $this->_datePaid = date('Y-m-d H:i:s');
            Application_Model_Operate::addOperate($this->_arrearsMoney, null, $this->_visitingNo, "用户给上门取件付款", $this->userId);
        } else if ($this->_interior == self::Interior_Payingmoney){
            $this->_interior = self::Interior_Launch;
            $this->_status = self::STATUS_Launch;
            $this->addBillLog(self::Interior_ArrearsFee);
            $this->addBillLog(self::Interior_Launch);
            $wayBillItem = Application_Model_wayBillItem::load($this->_wayId);
            $wayBillItem->Status = Application_Model_wayBillItem::STATUS_Processing;
            $wayBillItem->Interior = Application_Model_wayBillItem::Interior_Processing;
            $wayBillItem->DatePaid = date('Y-m-d H:i:s');
            $wayFee = Application_Model_WayFee::getByWayIdFeeType($this->_wayId, Application_Model_FeeType::EstimateSum);
            $wayFee->Money = $wayBillItem->ShipFee;
            $wayFee->save();
//            $wayBillItem->addOrNewFee(Application_Model_FeeType::EstimateSum,$wayBillItem->getFeeByType(Application_Model_FeeType::EstimateSum));
            $wayBillItem->save();
            foreach ($wayBillItem->getStoreItems() as $item) {
                $item->State = Application_Model_StoreItem::STATUS_Sended;
                $item->save();
            }
            Application_Model_Operate::addOperate($this->_arrearsMoney, null, $this->_visitingNo, "用户给上门取件（直发海外）补交款", $this->userId);
        }else if($this->_interior == self::Interior_Payfreight){
            $this->_interior = self::Interior_Complete;
            $this->_status = self::STATUS_Complete;
            $this->addBillLog(self::Interior_Complete);
            $storeItem = Application_Model_StoreItem::getAllbyLogistics($this->_inlandLogistics);
            foreach ($storeItem as $storeVal) {
                $storeVal->CnShipFee = 0;
                $storeVal->State = Application_Model_StoreItem::STATUS_InStored;
                $storeVal->save();            
            }
            Application_Model_Operate::addOperate($this->_arrearsMoney, null, $this->_visitingNo, "用户给上门取件（存入云仓库）补交款", $this->userId);
        }
    }
    
    public function canPay($userId) {
        if ($this->_userId != $userId)
            return FALSE;

        if ($this->_status != self::STATUS_WaitPay)
            return FALSE;

        return TRUE;
    }
    /**
    * 返回订单号
    */
   public static function getVisitingNumber($userId){
       return "Q".substr(date('Ymd',time()),2,6).Uuch_Util::base10to33(time().$userId);
   }
    /**
     * 根据运单ID返回该运单的费用明细
     * @param type $wayId
     * @return type
     */
    public static function getByWayId($wayId){
        return self::getDao()->queryAll(array('wayId'=>$wayId));
    }
    
    public static function ByWayId($wayId) {
        return self::getDao()->queryOne(array('wayId'=>$wayId));
    }


    /*根据用户id计算上门取件的件数*/
    public static function getCountByUserId($userId)
    {
        $where[" userId = "] = $userId;
        $where[" and status < "] = self::STATUS_Launch;
        $where[" and status != "] = self::STATUS_Cancel;
        $where[" and isDel = 0 and "] = 1;
        return self::getDao()->count($where);
    }
    
    public static function getProblemName(){
        switch ($this->_problem){
            case self::Problem_Default:
                return "初始化";
                break;
            case self::Problem_AppearProblem:
                return "出现问题";
                break;
            case self::Problem_SolveProblem:
                return "解决问题";
                break;
        }
    }
    /**
     * 返回所有的前台状态（数组）
     */
    public static function getStatusAll(){
        return array(
                   self::STATUS_WaitPay => "等待付款"
                ,  self::STATUS_Processing=>"等待受理"
                ,  self::STATUS_Confrimed=>"已受理"
                ,  self::STATUS_Delivery=>"已取件待入库"
                ,  self::STATUS_InStore=>"已入库"
                ,  self::STATUS_Payfreight=>"补交国内运费"                                
                ,  self::STATUS_Complete=>"已结算"                
                ,  self::STATUS_Payingmoney=>"补交款"
                ,  self::STATUS_Launch=>"已发国际"
                ,  self::STATUS_Cancel=>"取消退件"
                ,  self::STATUS_Lose=>"快递遗失"
                ,  self::STATUS_ChannelConflict=>"渠道冲突"
                ,  self::STATUS_DeliveryProblem=>"取件异常"
        );
    }
    /**
     *获取当前的对象的前台状态
     */
    public function getStatusName()
    {
        switch ($this->_status) {
            case self::STATUS_WaitPay:
                return "待付款";
                break;
            case self::STATUS_Processing:
                return "待受理";
                break;
            case self::STATUS_Confrimed:
                return "待取件";
                break;
            case self::STATUS_Delivery:
                return "待入库";
                break;
            case self::STATUS_InStore:
                return "已入库";
                break;
            case self::STATUS_Launch:
                return "已发海外";
                break;
            case self::STATUS_Cancel:
                return "取消";
                break;
            case self::STATUS_Lose:
                return "快递遗失";
                break;
            case self::STATUS_ChannelConflict:
                return "渠道冲突";
                break;
            case self::STATUS_DeliveryProblem:
                return "取件异常";
                break;
            case self::STATUS_Complete:
                return "已结算";
                break;
            case self::STATUS_Payfreight:
                return "补交国内运费";
                break;
            case self::STATUS_Payingmoney:
                return "补交款";
                break;
            default:
                return "未知状态";
                break;
        }
    }

    /**
     * 返回所有的后台状态（数组）
     */
    public static function getInteriorAll()
    {
        return array(
                   self::Interior_WaitPay => "未付款"
                ,  self::Interior_Processing=>"未受理"
                ,  self::Interior_Confrimed=>"已受理"
                ,  self::Interior_InformDelivery=>"已通知渠道"
                ,  self::Interior_Delivery=>"已取件"
                ,  self::Interior_InStore=>"已入库"
                ,  self::Interior_Payfreight=>"结算补交"
                ,  self::Interior_Complete=>"已结算"
                ,  self::Interior_Pack=>"已打包"
                ,  self::Interior_Inspections=>"已审单"
                ,  self::Interior_Payingmoney=>"补交款"
                ,  self::Interior_Launch=>"已发出"
                ,  self::Interior_Cancel=>"已取消"                
                ,  self::Interior_ShipOutTime=>"运送超期"
                ,  self::Interior_Lose=>"快递遗失"
                ,  self::Interior_DeliveryProblem=>"取件异常"
        );
    }
    /**
     *获取当前的对象的后台状态
     */
    public function getInteriorName()
    {
        switch ($this->_interior) {
            case self::Interior_WaitPay:
                return "未付款";
                break;
            case self::Interior_Processing:
                return "未受理";
                break;
            case self::Interior_Confrimed:
                return "已受理";
                break;
            case self::Interior_InformDelivery:
                return "通知渠道取件";
                break;
            case self::Interior_Delivery:
                return "已取件";
                break;
            case self::Interior_InStore:
                return "已入库";
                break;
            case self::Interior_ShipOutTime:
                return "运送超期";
                break;
            case self::Interior_Pack:
                return "已打包";
                break;
            case self::Interior_Inspections:
                return "已审单";
                break;
            case self::Interior_ArrearsFee:
                return "已交补款";
                break;
            case self::Interior_Lose:
                return "快递遗失";
                break;
            case self::Interior_DeliveryProblem:
                return "取件异常";
                break;
            case self::Interior_Launch:
                return "已发出";
                break;
            case self::Interior_Cancel:
                return "已取消";
                break;
            case self::Interior_Complete:
                return "已结算";
                break;
            case self::Interior_Payfreight:
                return "结算补交";
                break;
            case self::Interior_Payingmoney:
                return "补交款";
                break;
            default:
                return "未知状态（$this->_interior）";
                break;
        }
    }
    
    protected $_userItem;
    public function getUserInfo() {
        if ($this->_userItem == null) {
            $this->_userItem = Application_Model_User::load($this->_userId);
        }
        return $this->_userItem;
    }
        
    protected $_wayBillItem;
    public function getWayBill(){
        if($this->_wayBillItem == null){
            $this->_wayBillItem = Application_Model_wayBillItem::load($this->_wayId);
        }
        return $this->_wayBillItem;
    }

    protected $_cityItem;
    public function getCityByCityId()
    {
        if($this->_cityItem == null){
            $this->_cityItem = Application_Model_city::load($this->_inlandCityId);
        }
        return $this->_cityItem;
    }
    
    protected $_townItem;
    public function getTownBy()
    {
        if($this->_townItem == null){
            $this->_townItem = Application_Model_city::load($this->_inlandTownId);
        }
        return $this->_townItem;
    }

    public static function getVisitingAll($visitingSearch,$pagesize,$pageindex)
    {
//        var_dump($visitingSearch->getSearchFileds());
        return self::getDao()->queryPage($visitingSearch->getSearchFileds(), " dateCreated desc ", $pagesize, $pageindex);
    }
    
    public static function getproblemVisitingAll($visitingSearch,$pagesize,$pageindex,$id){
        return self::getDao()->queryPage($visitingSearch->getproblemSearchFileds($id), " dateCreated desc ", $pagesize, $pageindex);
    }

    public static function getProcount($visitingSearch,$id){
        return self::getDao()->count($visitingSearch->getproblemSearchFileds($id));
    }

    protected $_storeItem;
    public function getStoreItems()
    {
        if($this->_storeItem == null){
            $this->_storeItem = Application_Model_StoreItem::getAllbyLogistics($this->_inlandLogistics);
        }
        return $this->_storeItem;
    }
    
    private $_items;
    /**
     * 返回运单中所有的货物
     */
    public function getItems() {
        if ($this->_items == NULL) {
            $this->_items = Application_Model_WayItem::getByWayId($this->_wayId);
        }
        return $this->_items;
    }
    
    protected $_expressItem;
    public function getExpress()
    {
        if($this->_expressItem == null){
            $this->_expressItem = Application_Model_Express::load($this->_inlandShipType);
        }
        return $this->_expressItem;
    }

    /**
     * 取件商品入库
     */
    public function VisitingInStore($inlandLogistics)
    {
        $this->_status = self::STATUS_InStore;
        $this->_interior = self::Interior_InStore;
        $storeItem = Application_Model_StoreItem::getAllbyLogistics($inlandLogistics);
        foreach ($storeItem as $storeVal) {
            if($storeVal->CnShipFee > 0 && $storeVal->CnShipFee != null){
                $this->actualCnShipFee = $storeVal->CnShipFee;
            }
            $storeVal->State = Application_Model_StoreItem::STATUS_Bind;
            $storeVal->save();            
        }
        $this->inlandLogistics = $inlandLogistics;
        $this->save();
        $this->addBillLog(self::Interior_InStore);
        $this->LaunchWayBill();
    }
    /**
     * 入库完后启用国际运单
     * @return type
     */
    public function LaunchWayBill()
    {
        if($this->_isWay == 1){
            $wayBillItem = Application_Model_wayBillItem::load($this->_wayId);
            if(!$wayBillItem){
               return ; 
            }
            $storeItem = Application_Model_StoreItem::getAllbyLogistics($this->_inlandLogistics);
            foreach ($storeItem as $storeVal) {
                Application_Model_WayItem::addWayStoreItem($wayBillItem->id, $storeVal->id);
                if($storeVal->cnShipFee >= 0 && $storeVal->cnShipFee != null){
                    $inlandMoney = $storeVal->cnShipFee;
                    $wayBillItem->addOrNewFee(Application_Model_FeeType::CnShipFee, $inlandMoney);
                }
            }
        }
    }

    /**
     * 上门取件商品打包
     */
    public function PackVisiting($weight,$volume,$description,$shipFee)
    {
        $wayItem = Application_Model_wayBillItem::load($this->_wayId);
        if($wayItem != null){            
            $wayItem->ShipFee = $shipFee;
            $wayItem->save();
            if ($wayItem->IsVolume && $volume > $weight) {
                 $wayItem->addWeight(Application_Model_WeightType::EstimateWeight,$volume*1000);
            } else {
                 $wayItem->addWeight(Application_Model_WeightType::EstimateWeight,$weight*1000);
            }
            $wayItem->addWeight(Application_Model_WeightType::EstimateVolume,$volume*1000);
            $wayItem->addWeight(Application_Model_WeightType::Visiting_PackWeight,$weight*1000);
            $wayItem->addWeight(Application_Model_WeightType::Visiting_PackVolume,$volume*1000);
            if($description != null) {
                $this->addBillLog(Application_Model_WayLog::Type_BillVolume, $description);
            }
            $this->_interior = Application_Model_VisitingServer::Interior_Pack;
            $this->save();
            $this->addBillLog(Application_Model_VisitingServer::Interior_Pack);
            return 1;
        }else{
            return 0;
        }               
    }
    /*
     * 发往国外
     */
    public function SendTo()
    {
        if($this->_status == self::STATUS_InStore && $this->_interior == self::Interior_ArrearsFee){
            $this->_status = self::STATUS_Launch;
            $this->_interior = self::Interior_Launch;
            $this->save();
        }
    }

    private $_weights;
    /**
     * 返回运单的所有重量信息
     * @return type
     */
    public function getWeights() {
        if ($this->_weights == NULL) {
            $this->_weights = Application_Model_WayWeight::getByWayId($this->_id);
        }
        return $this->_weights;
    }
    /**
     * 添加一个重量信息
     * @param type $type
     * @param type $weight
     */
    public function addWeight($type, $weight) {
        $weightItem = new Application_Model_WayWeight();
        $weightItem->Type = $type;
        $weightItem->Weight = $weight;
        $weightItem->WayId = $this->_id;
        $weightItem->save();
        $weights = $this->getWeights();
        $weights[] = $weightItem;
    }
    private $_fees;
    /**
     * 返回运单的费用明细
     */
    public function getFees() {
        if ($this->_fees == NULL) {
            $this->_fees = Application_Model_WayFee::getByWayId($this->_id);
        }
        return $this->_fees;
    }
    /**
     * 添加一个费用
     */
    public function addFee($feeType, $money) {
        $fees = $this->getFees();
        $fee = new Application_Model_WayFee();
        $fee->FeeType = $feeType;
        $fee->Money = $money;
        $fee->WayId = $this->_id;
        $fee->save();
        $fees [] = $fee;
    }
    /**
     * 取件取消
     */
    public function cancelVisiting()
    {
        if($this->_status == self::STATUS_WaitPay || $this->_status == self::STATUS_Processing || $this->_status == self::STATUS_DeliveryProblem){
            if($this->_status == self::STATUS_Processing || $this->_status == self::STATUS_DeliveryProblem){
                if($this->_isWay == 1){
                    $cancelMoney = $this->_advanceMoney;
                }else{
                    $cancelMoney = $this->_guaranteeFee;
                }
                $account = Application_Model_UserAccount::load($this->_userId);
                $history = new Application_Model_UserAccountHistory();
                $history->Type = Application_Model_UserAccountHistory::TYPE_RECHARGE_MONEY;
                $history->BeforeMoney = $account->Money;
                $history->AfterMoney = $account->Money + $cancelMoney;
                $history->Comment = '取消上门取件退款';
                $history->DateCreated = date('Y-m-d H:i:s');
                $history->RelaseId = $this->_id;
                $history->BeforeScore = $account->Score;
                $history->State = Application_Model_UserAccountHistory::STATE_MONEY;
                $history->AfterScore = $account->Score;
                $history->AccountId = $account->Id;
                $history->save();

                $account->Money += $cancelMoney;
                $account->save();
            }
            $this->_status = self::STATUS_Cancel;
            $this->_interior = self::Interior_Cancel;
            $this->save();
            return 1;
        }else{
            return 0;
        }
    }
    /**
     * 删除取件
     */
    public function delVisiting()
    {
        if($this->_status == self::STATUS_Cancel && $this->_isDel != 1){
            $this->_isDel = 1;
            $this->save();
            return 1;
        }else{
            return 0;
        }
    }
    public function addProblemWay($status,$schedule)
    {
        $type = Application_Model_ProblemWay::Type_Visiting;
        $problemItem = Application_Model_ProblemWay::getByTypeWayId($this->_id,$type);
        if(!$problemItem){
            $problemItem = new Application_Model_ProblemWay();
        }
        $problemItem->wayId = $this->_id;
        $problemItem->status = $status;
        $problemItem->schedule = $schedule;
        $problemItem->type = $type;
        $problemItem->save();
    }
    
    public function addProblemSchedule($content,$schedule,$crdate = null)
    {
        $problemScheduleItem = new Application_Model_ProblemSchedule();
        $problemScheduleItem->wayId = $this->_id;
        $problemScheduleItem->content = $content;
        $problemScheduleItem->operateName = Uuch_Util::getUserNikeName();
        $problemScheduleItem->schedule = $schedule;
        $problemScheduleItem->dateCreated = ($crdate==null?date("Y-m-d H:i:s"):$crdate);
        $problemScheduleItem->type = Application_Model_ProblemSchedule::Type_Visiting;
        $problemScheduleItem->save();
    }
    public function addProblem($content)
    {
        Application_Model_Operate::addOperate(0, null, $this->_visitingNo, "异常上门取件发送站内信和邮件",  $this->_userId);
        $title = "尊敬的客户，您好！您的上门取件($this->_visitingNo)出现问题。";
        $type = Application_Model_problem::TYPE_VISITING;
        $issuetype = "1";
        Application_Model_problem::addProblem($this->_userId,$this->_id,$type,$issuetype,$title,$content);
        $this->addProblemWay(Application_Model_ProblemWay::Problem_StayUser, null);
        $this->addProblemSchedule("上门取件出现问题",  null);
        $messageItem = new Application_Model_Mail();
        $messageItem->title = $title;
        $messageItem->userId = $this->_userId;
        $messageItem->type = 2;
        $messageItem->status = 0;
        $messageItem->message = $content;
        $messageItem->dateCreated = date("Y-m-d H:i:s");
        $messageItem->save();
        $userItem = Application_Model_User::load($this->_userId);
        Application_Model_Email::sendMail($this->_userId, $userItem->email, $title, $content);
        return true;
    }
    
    public function addProblemUser($content)
    {
        $issuetype = "2";
        Application_Model_problem::addProblem($this->_userId,$this->_id,Application_Model_problem::TYPE_VISITING,$issuetype,null,$content);
        $problemItem = Application_Model_ProblemWay::getByTypeWayId($this->_id,Application_Model_ProblemWay::Type_Visiting);
        if($problemItem->status == Application_Model_ProblemWay::Problem_StayUser || $problemItem->status == Application_Model_ProblemWay::Problem_StayUuch){
            $this->addProblemWay(Application_Model_ProblemWay::Problem_StayUuch, null);
            $this->addProblemSchedule("问题协商中",  null);
        }
        return true;
    }
    
    public function addBillLog($interior, $description = null) {
        $billLogItem = Application_Model_WayLog::getByWayIdInteriorType($this->_id, $interior,  Application_Model_WayLog::Type_Visiting);
        if (!$billLogItem) {
            $billLogItem = new Application_Model_WayLog();
            $billLogItem->wayId = $this->_id;
            $billLogItem->operateType = $interior;
        }        
        $billLogItem->dateCreated = date("Y-m-d H:i:s");
        $billLogItem->operator = Uuch_Util::getUserNikeName();
        if ($description != null) {
            $billLogItem->description = $description;
        } else {
            $billLogItem->description = "上门取件状态更改为：" . $this->getInteriorName();
        }        
        $billLogItem->type = Application_Model_WayLog::Type_Visiting;        
        $billLogItem->save();
    }
    
    public function delLog() {
        $logItem = Application_Model_WayLog::getDao()->queryAll(array("wayId" => $this->_id, "and operateType<200 and operateType > " => $this->_interior));
        if ($logItem) {
            foreach ($logItem as $logVal) {
                $logVal->delete();
            }
        }
    }

    public function getInTypeName() {
        return '上门取件';
    }
    
    public static function getByShipNo($logistics)
    {
        return self::getDao()->queryOne(array("inlandLogistics"=>$logistics, "and isDel = " => 0));
    }
   
    public static function getProblemVisting(){
        $and = "";
        $where[$and." (isDel is null or isDel = 0) and "] = 1;
        $and = " and ";
        $where[$and." problem is not null  and "] = 1;
        $and = " and ";
        return self::getDao()->queryAll($where);
    }
    
    public static function getCountByInteriorTime($interior,$time,$isWay=null,$problem = null)
    {
        $and = "";
        if($interior !==null){
            $where[" interior = "] = $interior;
            $and = " and ";
        }
        if($time !== null){
            $where[$and.' dateCreated >='] = date("Y-m-d") . " 00:00:00";
            $where[' and dateCreated <='] = date("Y-m-d") . " 23:59:59";
            $and = " and ";
        }
        if($isWay !== null){
            $where[$and.' isWay = '] = $isWay;
            $and = " and ";
        }
        if($problem !== null){
            $where[$and.' problem = '] = $problem;
            $and = " and ";
        } else {
            $where[$and." (problem != 3 or problem is null ) and "] = 1;
            $and = " and ";
        }
        $where[$and." (isDel is null or isDel = 0) and "] = 1;
//        var_dump($where);exit;
        return self::getDao()->count($where);
    }
    
    public static function getPaylink($id){
        $visitingItem = Application_Model_VisitingServer::load($id);
        $link = Application_Model_RepayLink::getByRelationIdType($visitingItem->Id, Application_Model_PayBill::TYPE_Visiting);
        if($link){
            $link->delete();
        }
        $weight = Application_Model_WayWeight::getVweightByWayId($visitingItem->wayId);        
        $wayItem = Application_Model_wayBillItem::load($visitingItem->wayId);        
        $prices = Application_Model_ExpressPrice::getPricesByCity($wayItem->state);
        $SortKey = 0;
        
        foreach ($prices as $item) {
            if($item->ExpressId == $wayItem->ShipType){
                $SortKey = $item->getMoneyByweight($weight);
                break;
            }
        }    
        $wayItem->addOrNewFee(Application_Model_FeeType::EstimateShipFee,$SortKey);
        $money = $wayItem->ShipFee - $visitingItem->advanceMoney; 
        //$SortKey+$wayItem->getFeeByType(Application_Model_FeeType::VacuumSeviceFee)+$wayItem->getFeeByType(Application_Model_FeeType::WoodenFee)+$wayItem->getFeeByType(Application_Model_FeeType::RatePremiumFee)+$wayItem->getFeeByType(Application_Model_FeeType::CnShipFee)+$wayItem->getFeeByType(Application_Model_FeeType::RemoteFee)-$visitingItem->advanceMoney;
        if($money > 0){
            $payLink = Application_Model_RepayLink::createRepayLink("运单".$wayItem->billNo."补交款", null, Application_Model_PayBill::TYPE_Visiting, $visitingItem->Id, $money, $visitingItem->UserId);        
            $payLink->save();
            return $payLink;
        }                
   }
   
    public function getPayLinkByType($type)
    {
        $payLinkItem = Application_Model_RepayLink::getByRelationIdType($this->_id, Application_Model_PayBill::TYPE_Visiting);
        return $payLinkItem->getPayLink(Application_Model_PayBill::TYPE_REPAY_LINK);
    }
   
   public function getlocationName() {
      $result = Application_Model_StoreLocation::getDao()->queryAll(array("userId" => $this->_userId));
      if ($result) {
         $locationName = "";
         foreach ($result as $value) {
            $locationName.= $value->locationNo . ",";
         }
         return $locationName;
     } else {
        return "还没有绑定仓库位，请耐心寻找。";
     }
  }
   
  public static function countVisiting($visitingSearch) {
      return Application_Model_VisitingServer::getDao()->count($visitingSearch->getSearchFileds());
  }
    
}
     